package com.unclesweet.crmsystem.activity.web;

import com.unclesweet.crmsystem.activity.model.Activity;
import com.unclesweet.crmsystem.activity.service.ActivityService;
import com.unclesweet.crmsystem.commons.model.Constants;
import com.unclesweet.crmsystem.commons.model.ResponseResult;
import com.unclesweet.crmsystem.commons.util.DateUtils;
import com.unclesweet.crmsystem.commons.util.UUIDUtils;
import com.unclesweet.crmsystem.settings.model.User;
import com.unclesweet.crmsystem.settings.service.UserService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/workbench/activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index(Model model) {
        return "/workbench/activity/index";
    }

    @RequestMapping("/loadActivity")
    @ResponseBody
    public ResponseResult loadActivity(String name, String owner, String startDate, String endDate, Integer page, Integer pageSize) {
        //定义基础变量
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        int startIndex = (page - 1) * pageSize;
        //获取数据
        List<Activity> activities = activityService.queryConditionWithPage(name, owner, startDate, endDate, startIndex, pageSize);
        int count = activityService.queryConditionCount(name, owner, startDate, endDate);
        //保存数据
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(Constants.STATUS_OK);
        Map<String, Object> map = new HashMap<>();
        map.put("activities", activities);
        map.put("count", count);
        responseResult.setData(map);
        //返回数据
        return responseResult;
    }

    @RequestMapping("/addActivity")
    @ResponseBody
    @Transactional
    public ResponseResult addActivity(Activity activity, HttpSession session){
        ResponseResult responseResult = new ResponseResult();
        //获取当前用户
        User user = (User) session.getAttribute(Constants.SESSION_USER);

        //设置当前创建者
        activity.setCreateBy(user.getId());
        //设置当前创建时间
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        //设置当前活动的标识
        activity.setId(UUIDUtils.getUUID());

        //插入活动
        int flag = activityService.addActivity(activity);
        if(flag > 0){
            responseResult.setCode(Constants.STATUS_OK);
            responseResult.setMsg("插入成功");
        }else{
            responseResult.setCode(Constants.STATUS_ERROR);
            responseResult.setMsg("插入失败");
        }

        return responseResult;
    }

    @RequestMapping("/oneActivity")
    @ResponseBody
    public ResponseResult oneActivity(String id){
        ResponseResult responseResult = new ResponseResult();
        //查询单个活动
        Activity activity = activityService.queryById(id);
        if(activity != null){
            responseResult.setCode(Constants.STATUS_OK);
            responseResult.setData(activity);
        }else{
            responseResult.setCode(Constants.STATUS_ERROR);
            responseResult.setMsg("用户不存在");
        }
        return responseResult;
    }

    @RequestMapping("/editActivity")
    @ResponseBody
    @Transactional
    public ResponseResult editActivity(Activity activity,HttpSession session){
        System.out.println(activity);
        ResponseResult responseResult = new ResponseResult();
        //获取当前用户信息
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //设置当前活动编辑者
        activity.setEditBy(user.getId());
        //设置当前活动编辑时间
        activity.setEditTime(DateUtils.formatDateTime(new Date()));
        //修改活动
        int count = activityService.updateActivity(activity);
        if(count > 0){
            responseResult.setCode(Constants.STATUS_OK);
            responseResult.setMsg("修改成功");
        }else{
            responseResult.setCode(Constants.STATUS_ERROR);
            responseResult.setMsg("修改失败");
        }
        return responseResult;
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    @Transactional
    public ResponseResult batchDelete(String[] ids){
        ResponseResult responseResult = new ResponseResult();
        if(ids != null){
            //执行批量删除
            int count = activityService.deleteBatchByIds(ids);
            if(count > 0){
                responseResult.setCode(Constants.STATUS_OK);
                responseResult.setMsg("成功删除"+count+"条数据！");
            }else{
                responseResult.setCode(Constants.STATUS_ERROR);
                responseResult.setMsg("删除失败！");
            }
        }else{
            responseResult.setCode(Constants.STATUS_ERROR);
            responseResult.setMsg("没有选择任何数据！拒绝操作！");
        }
        return responseResult;
    }

    @RequestMapping("/allUser")
    @ResponseBody
    public ResponseResult allUser(){
        ResponseResult responseResult = new ResponseResult();
        List<User> users = userService.queryAll();
        if(users != null){
            responseResult.setCode(Constants.STATUS_OK);
            responseResult.setData(users);
        }else{
            responseResult.setCode(Constants.STATUS_ERROR);
            responseResult.setMsg("用户列表为空！");
        }
       return responseResult;
    }

    @RequestMapping("/exportActivity")
    public void exportActivity(HttpServletResponse response,String[] ids){
        List<Activity> activities = null;

        if(ids == null){
            activities = activityService.queryAll();
        }else{
            activities = activityService.queryBatchByIds(ids);
            System.out.println(activities.size());
        }

        //1、创建工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2、创建工作表
        HSSFSheet sheet = workbook.createSheet("导出的活动列表");
        //3、创建标题行(第一行)
        HSSFRow rowHeader = sheet.createRow(0);
        //第一行创建单元格并且填充内容
        HSSFCell cellHeader = rowHeader.createCell(0);
        cellHeader.setCellValue("活动名称");
        cellHeader = rowHeader.createCell(1);
        cellHeader.setCellValue("所有者名称");
        cellHeader = rowHeader.createCell(2);
        cellHeader.setCellValue("起始时间");
        cellHeader = rowHeader.createCell(3);
        cellHeader.setCellValue("结束时间");
        cellHeader = rowHeader.createCell(4);
        cellHeader.setCellValue("活动描述");
        cellHeader = rowHeader.createCell(5);

        //4、循环遍历数据并且写入单元格对象中
        int i = 1;    // 起始行号
        for(Activity activity:activities){
            //创建行对象
            HSSFRow row = sheet.createRow(i);

            //创建单元格
            HSSFCell cell = row.createCell(0);
            cell.setCellValue(activity.getName());
            cell = row.createCell(1);
            cell.setCellValue(activity.getOwner());
            cell = row.createCell(2);
            cell.setCellValue(activity.getStartDate());
            cell = row.createCell(3);
            cell.setCellValue(activity.getEndDate());
            cell = row.createCell(4);
            cell.setCellValue(activity.getDescription());
            i++;

            //设置自动换行
            /*HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            cell.setCellStyle(cellStyle);*/
        }

        //6、获取response对象的输出流对象，输出活动数据到留中
        try {
            //获取输出流
            OutputStream outputStream = response.getOutputStream();
            //设置文件名称，并且设置编码为utf-8
            String filename = URLEncoder.encode(("市场活动-"+System.currentTimeMillis()+".xls"),"utf-8");
            //设置响应头，通知浏览器当前文件名称文   以下载的方式操作
            response.setHeader("content-disposition","attachment;filename="+filename);
            //将当前excel工作薄添加到输出流中
            workbook.write(outputStream);
            //刷新输出流
            outputStream.flush();
            //关闭输出流
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/importActivity")
    @ResponseBody
    public ResponseResult importActivity(HttpSession session, MultipartFile multipartFile){
        ResponseResult responseResult = new ResponseResult();
        List<Activity> activities = new ArrayList<>();
        //获取当前用户
        User user = (User) session.getAttribute(Constants.SESSION_USER);

        try {
            //获取当前文件的输入流
            InputStream inputStream = multipartFile.getInputStream();
            //获取工作薄
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            //获取表
            HSSFSheet sheet = workbook.getSheetAt(0);
            HSSFRow row;
            HSSFCell cell;
            //循环遍历，活动数据加载到集合
            for(int i = 1;i <= sheet.getLastRowNum();i++){
                Activity activity = new Activity();
                activity.setCreateTime(DateUtils.formatDateTime(new Date()));
                activity.setCreateBy(user.getId());
                activity.setOwner(user.getId());
                activity.setId(UUIDUtils.getUUID());

                //跳转到指定的行
                row = sheet.getRow(i);

                //依次读取单元格的信息
                String name = row.getCell(0).getStringCellValue();
                activity.setName(name);

                String startDate = row.getCell(1).getStringCellValue();
                activity.setStartDate(startDate);

                String endDate =row.getCell(2).getStringCellValue();
                activity.setEndDate(endDate);

                String cost = String.valueOf(row.getCell(3).getNumericCellValue());
                activity.setCost(cost);

                String description = row.getCell(4).getStringCellValue();
                activity.setDescription(description);

                activities.add(activity);
            }
        } catch (IOException e) {
            e.printStackTrace();
            responseResult.setCode(Constants.STATUS_ERROR);
            responseResult.setMsg("系统繁忙，请稍后再试！");
        }

        //判断活动数据集合是否为空
        if(activities.size() > 0){
            //执行批量插入
            int count = activityService.addBatchByActivities(activities);
            if(count > 0){
                responseResult.setCode(Constants.STATUS_OK);
                responseResult.setMsg("成功导入"+count+"条数据");
            }else{
                responseResult.setCode(Constants.STATUS_ERROR);
                responseResult.setMsg("系统繁忙，请稍后再试！");
            }
        }

        return responseResult;
    }

}